package com.example.yupao.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.yupao.enums.StatusEnum;
import com.example.yupao.exception.BusinessException;
import com.example.yupao.model.domain.Tag;
import com.example.yupao.model.pojo.TagSearchChildren;
import com.example.yupao.model.response.TagSearchResponse;
import com.example.yupao.service.TagService;
import com.example.yupao.mapper.TagMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 86138
 * @description 针对表【tag】的数据库操作Service实现
 * @createDate 2024-09-11 10:08:42
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag>
        implements TagService {

    @Override
    public List<TagSearchResponse> search() {

        List<Tag> tagList = this.list();

        if (CollectionUtil.isEmpty(tagList)){
            throw new BusinessException(StatusEnum.SYSTEM_ERROR,"系统异常,请稍后重试~");
        }

        List<TagSearchResponse> responseList = new ArrayList<>();

        //TODO 未来优化 O(n^2)
        tagList.stream().forEach(tag -> {
            //如果为父标签,则新建一个response
            if (tag.getIsParent() == 1) {
                TagSearchResponse response = new TagSearchResponse();
                response.setText(tag.getTagName());
                List<TagSearchChildren> childrenList = new ArrayList<>();
                tagList.stream().forEach(_tag -> {
                    if (_tag.getIsParent() == 0 && _tag.getParentId() == tag.getId()){
                        TagSearchChildren children = new TagSearchChildren();
                        children.setId(_tag.getId());
                        children.setText(_tag.getTagName());
                        childrenList.add(children);
                    }
                });
                response.setChildren(childrenList);
                responseList.add(response);
            }
        });
        return responseList;
    }
}




